/*
 * @Author: 13938960424 1758142861@qq.com
 * @Date: 2023-10-27 15:14:24
 * @LastEditors: 13938960424 1758142861@qq.com
 * @LastEditTime: 2023-11-05 17:44:23
 * @FilePath: /sjf/new-xshell/muduo/source/socket.hpp
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#ifndef _M_SOCKET_H__
#define _M_SOCKET_H__

#include <iostream>
#include <unistd.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "../log/logger.hpp"

#define MAX_LISTEN 32

class Socket
{
public:
    Socket():_socket_fd(-1)
    {}
    Socket(int sock):_socket_fd(sock)
    {}
    ~Socket() { Close(); }
    int Fd() { return _socket_fd; }
    //创建套接字
    bool Create()
    {
        _socket_fd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);//默认最后一个参数给0,让其自己选择
        if(_socket_fd < 0)
        {
            ERR_LOG("create socket error!");
            return false;
        }
        return true;
    }
    //绑定套接字信息
    bool Bind(const std::string& ip,const uint64_t& port)
    {
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_addr.s_addr = inet_addr(ip.c_str());
        addr.sin_port = htons(port);
        socklen_t len = sizeof(struct sockaddr_in);
        int ret = bind(_socket_fd,(struct sockaddr*)&addr,len);
        if(ret < 0)
        {
            ERR_LOG("socket bind error!");
            return false;
        }
        return true;
    }
    //进行监听
    bool Listen(int backlog = MAX_LISTEN)
    {
        int ret = listen(_socket_fd,backlog);
        if(ret < 0)
        {
            ERR_LOG("socket listen error!");
            return false;
        }
        return true;
    }
    //发起连接
    bool Connect(const std::string& ip,const uint64_t& port)
    {
        struct sockaddr_in addr;
        addr.sin_family = AF_INET;
        addr.sin_addr.s_addr = inet_addr(ip.c_str());
        addr.sin_port = htons(port);
        socklen_t len = sizeof(struct sockaddr_in);
        int ret = connect(_socket_fd,(const sockaddr*)&addr,len);
        if(ret < 0)
        {
            ERR_LOG("socket connect error!");
            return false;
        }
        return true;
    }
    //获取新连接
    int Accept()
    {
        int fd = accept(_socket_fd,NULL,NULL);
        if(fd < 0)
        {
            ERR_LOG("socket accept error!");
            return -1;
        }
        return fd;
    }
    //接收数据
    ssize_t Recv(void* buf,size_t len,int flag = 0)
    {
        ssize_t ret = recv(_socket_fd,buf,len,flag);
        if(ret <= 0)
        {
            if(errno == EAGAIN || errno == EINTR)
                return 0;
            ERR_LOG("socket recv error!");
            return -1;
        }
        return ret;
    }
    ssize_t RecvNonblack(void* buf,size_t len)
    {
        return Recv(buf,len,MSG_DONTWAIT);
    }
    //发送数据
    ssize_t Send(const void* buf,size_t len,int flag = 0)
    {
        ssize_t ret = send(_socket_fd,buf,len,flag);
        if(ret <= 0)
        {
            if(errno == EAGAIN || errno == EINTR)
                return 0;
            ERR_LOG("socket send error!");
            return -1;
        }
        DBG_LOG("%s",buf);
        return ret;
    }
    ssize_t SendNonblack(const void* buf,size_t len)
    {
        if(len == 0) return 0;
        return Send(buf,len,MSG_DONTWAIT);
    }
    //关闭套接字
    void Close()
    {
        if(_socket_fd != -1)
        {
            close(_socket_fd);
            _socket_fd = -1;
        }
            
    }
    //创建一个服务器监听连接
    bool CreateServer(uint16_t port, const std::string &ip = "0.0.0.0", bool block_flag = false) 
    {
        //1. 创建套接字，2. 绑定地址，3. 开始监听，4. 设置⾮阻塞， 5. 启动地址重⽤
        if (Create() == false) 
            return false;
        if (block_flag) Nonblack();
        if (Bind(ip, port) == false) 
            return false;
        if (Listen() == false) 
            return false;
        ReuseAddress();
        return true;
 }
    //创建一个客户端请求连接
    bool CreateClient(const std::string& ip,uint16_t port)
    {
        if(Create() == false) 
            return false;
        if(Connect(ip,port) == false) 
            return false;
        return true;
    }
    //设置非阻塞
    void Nonblack()
    {
        int flag = fcntl(_socket_fd,F_GETFL,0);
        fcntl(_socket_fd,F_SETFL,flag | O_NONBLOCK);
    }
    //开启端口复用
    void ReuseAddress()
    {
        int val = 1;
        setsockopt(_socket_fd,SOL_SOCKET,SO_REUSEADDR,(void*)&val,sizeof(int));
        val = 1;
        setsockopt(_socket_fd,SOL_SOCKET,SO_REUSEPORT,(void*)&val,sizeof(int));
    }
private:
    int _socket_fd;
};

#endif